import { cloneDeep, includes } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import _ from 'lodash-es'
import { checkRoles } from '@/stores/roles'


export const useOrderStore = () => {
    const router = useRouter()
    const userStore = useUserStore()
    const languageJson = inject('languageJson')
    const languageType = inject('languageType')
    const state = reactive({
        excelsta: false,
        activestatus: 0,
        status: [{
            value: 0,
            label: '全部',
            ncount: 0
        }, {
            value: 1,
            label: '预约',
            count: 0
        }, {
            value: 2,
            label: '未结算',
            count: 0
        }, {
            value: 3,
            label: '已结算',
            count: 0
        }, {
            value: 5,
            label: '取消',
            count: 0
        }],

        leaguefilter: [],
        matchfilter: [],

        filterdialog: false,
        filterForm: {
            sport_type: "soccer",
            order_status: 0,
            league_name: "all",
            homeaway: 'all',
            task_type: 'all',
            home_away: {
                home: "",
                away: ""
            },
            order_time: [],
            begin_time: "2024-11-01 04:46:12",
            end_time: "2024-11-29 04:46:12",
            match_time: [],
            match_begin_time: "2024-11-01 04:46:12",
            match_end_time: "2024-11-29 04:46:12",
            its_me: checkRoles(userStore.user.roles, 'share') ? -1 : 1,
            page: 1,
            page_size: 20
        },

        orderLoading: false,
        orderList: [],
        orderListtotal: 0,

        activetype: 0,

        userList: [],



    })

    const getleaguefilter = () => {
        let body = {
            params: {
                sport_type: state.filterForm.sport_type
            }
        }
        http.get('/order/league_filter', body).then((res) => {
            state.leaguefilter = res.data
            changeleaguename()
        })
    }

    const getorderfiltercount = () => {
        let body = {
            sport_type: state.filterForm.sport_type,
            league_name: state.filterForm.league_name,
            home_away: {
                home: "",
                away: ""
            },
            task_type: state.filterForm.task_type,
            its_me: state.filterForm.its_me,
            begin_time: state.filterForm.order_time[0],
            end_time: state.filterForm.order_time[1],
            match_begin_time: state.filterForm.match_time[0],
            match_end_time: state.filterForm.match_time[1],
        }
        if (body.league_name == 'all') {
            delete body.league_name
        }
        if (body.task_type == 'all') {
            delete body.task_type
        }
        if (body.its_me == -1) {
            delete body.its_me
        }
        if (state.filterForm.homeaway == 'all') {
            delete body.home_away
        } else {
            let parts = state.filterForm.homeaway.split("-vs-");
            let beforeVs = parts[0];
            let afterVs = parts[1];
            state.matchfilter.forEach(item => {
                if (item.home == beforeVs && item.away == afterVs) {
                    body.home_away = item
                }
            });
        }
        http.post('/order/order_filter_count', body).then((res) => {

            let a = [{
                value: 0,
                label: '全部',
                count: res.data.all_task_count
            }, {
                value: 1,
                label: '预约',
                count: res.data.reservation_task_count
            }, {
                value: 2,
                label: '未结算',
                count: res.data.not_check_task_count
            }, {
                value: 3,
                label: '已结算',
                count: res.data.check_success_task_count
            }, {
                value: 5,
                label: '取消',
                count: res.data.cancel_task_count
            }]
            state.status = a

        })
    }

    const changeactivestatus = (value) => {
        state.activestatus = value
        state.filterForm.order_status = state.activestatus
        getorderList()
    }

    const openOrderfilter = () => {
        state.filterdialog = true

    }

    const changeleaguename = () => {
        let a = []
        if (state.filterForm.league_name == 'all') {
            Object.keys(state.leaguefilter).forEach(key => {
                a = [...a, ...state.leaguefilter[key].list]
            });
        } else {
            a = state.leaguefilter[state.filterForm.league_name].list
        }
        state.matchfilter = a
        state.filterForm.homeaway = 'all'
    }

    const getTimerange = () => {
        let a = getBeijingWeekDates()
        state.filterForm.begin_time = a.start
        state.filterForm.end_time = a.end
        state.filterForm.match_begin_time = a.start
        state.filterForm.match_end_time = a.end
        state.filterForm.order_time = [a.start, a.end]
        if (state.activetype == 0) {

            state.filterForm.match_time = [a.start, a.end]
        }



    }

    const getBeijingWeekDates = () => {
        const now = new Date();

        // 获取当前年份和月份
        const year = now.getFullYear();
        const month = now.getMonth(); // 当前月份（从0开始，即0是1月，11是12月）

        // 获取本月1号的日期
        const firstDayOfMonth = new Date(year, month, 1);
        firstDayOfMonth.setHours(12, 0, 0, 0); // 设置为12:00:00中午

        // 获取本月最后一天的日期
        const lastDayOfMonth = new Date(year, month + 1, 0); // 获取下月的第0天，即为本月的最后一天
        lastDayOfMonth.setHours(12, 0, 0, 0); // 设置为12:00:00中午

        // 格式化日期函数
        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        // 返回日期范围
        let result = {
            start: `${formatDate(firstDayOfMonth)} 12:00:00`,
            end: `${formatDate(lastDayOfMonth)} 12:00:00`
        };

        return result;
    }

    const filterReset = () => {
        if (state.activetype == 0) {
            state.filterForm = {
                sport_type: "soccer",
                order_status: 0,
                league_name: "all",
                homeaway: 'all',
                home_away: {
                    home: "",
                    away: ""
                },
                task_type: 'all',
                order_time: [],
                begin_time: "2024-11-01 04:46:12",
                end_time: "2024-11-29 04:46:12",
                match_time: [],
                its_me: checkRoles(userStore.user.roles, 'share') ? -1 : 1,
                match_begin_time: "2024-11-01 04:46:12",
                match_end_time: "2024-11-29 04:46:12",
                page: 1,
                page_size: 20
            }
        } else {
            state.filterForm = {
                user_name: '',
                sport_type: "soccer",
                order_status: 0,
                league_name: "all",
                homeaway: 'all',
                home_away: {
                    home: "",
                    away: ""
                },
                order_time: [],
                begin_time: "2024-11-01 04:46:12",
                end_time: "2024-11-29 04:46:12",
                page: 1,
                page_size: 20
            }
        }

        state.activestatus = state.filterForm.order_status
        state.filterdialog = false
        initData()
    }

    const clicksubmit = () => {
        state.filterdialog = false
        state.activestatus = state.filterForm.order_status
        if (state.activetype == 1) {
            getbctypeorderList()
        } else {
            getorderList()
            getorderfiltercount()
        }

    }

    const getorderList = () => {
        if (state.activetype == 0) {
            state.orderLoading = true
            let body = {
                sport_type: state.filterForm.sport_type,
                order_status: state.filterForm.order_status,
                league_name: state.filterForm.league_name,
                home_away: {
                    home: "",
                    away: ""
                },
                task_type: state.filterForm.task_type,
                begin_time: state.filterForm.order_time[0],
                end_time: state.filterForm.order_time[1],
                match_begin_time: state.filterForm.match_time[0],
                match_end_time: state.filterForm.match_time[1],
                its_me: state.filterForm.its_me,
                page: state.filterForm.page,
                page_size: state.filterForm.page_size
            }
            if (body.league_name == 'all') {
                delete body.league_name
            }
            if (body.its_me == -1) {
                delete body.its_me
            }
            if (state.filterForm.homeaway == 'all') {
                delete body.home_away
            } else {
                let parts = state.filterForm.homeaway.split("-vs-");
                let beforeVs = parts[0];
                let afterVs = parts[1];
                state.matchfilter.forEach(item => {
                    if (item.home == beforeVs && item.away == afterVs) {
                        body.home_away = item
                    }
                });
            }
            console.log(body);

            http.post('/order/order_list_bytask_data', body).then((res) => {
                state.orderList = res.data.list
                state.orderListtotal = res.data.total
                state.orderLoading = false
            })
        } else {
            getbctypeorderList()
        }

    }

    const getbctypeorderList = () => {
        state.orderLoading = true
        let body = {
            user_name: state.filterForm.user_name,
            sport_type: state.filterForm.sport_type,
            order_status: state.filterForm.order_status,
            league_name: state.filterForm.league_name,
            home_away: {
                home: "",
                away: ""
            },
            begin_time: state.filterForm.order_time[0],
            end_time: state.filterForm.order_time[1],
            page: state.filterForm.page,
            page_size: state.filterForm.page_size
        }
        if (body.league_name == 'all') {
            delete body.league_name
        }
        if (state.filterForm.homeaway == 'all') {
            delete body.home_away
        } else {
            let parts = state.filterForm.homeaway.split("-vs-");
            let beforeVs = parts[0];
            let afterVs = parts[1];
            state.matchfilter.forEach(item => {
                if (item.home == beforeVs && item.away == afterVs) {
                    body.home_away = item
                }
            });
        }

        http.post('/order/member_order_list', body).then((res) => {
            console.log(res);

            state.orderList = res.data.list
            state.orderListtotal = res.data.total
            state.orderLoading = false
            state.status = [{
                value: 0,
                label: '已结算',
                count: res.data.total
            }]
        })
    }

    const getuserLists = () => {
        http.get('/member/member_list?page=1&page_size=9999&login_status=2').then((res) => {
            if (res.data.list.length > 0) {
                state.userList = res.data.list.map(item => {
                    return { value: item.user_name, label: item.user_name }
                })
                state.filterForm.user_name = state.userList[0].value
                getbctypeorderList()
            } else {
                ElMessage({
                    message: '暂无账号',
                    type: 'warning',
                })
            }


        })
    }

    const gethandicapname = (sport_type, pk_odds_key) => {
        return pk_odds_key
    }

    const saveExell = () => {
        if (state.orderListtotal != 0) {
            if (state.activetype == 0) {
                let body = {
                    sport_type: state.filterForm.sport_type,
                    order_status: state.filterForm.order_status,
                    league_name: state.filterForm.league_name,
                    home_away: {
                        home: "",
                        away: ""
                    },
                    task_type: state.filterForm.task_type,
                    begin_time: state.filterForm.order_time[0],
                    end_time: state.filterForm.order_time[1],
                    match_begin_time: state.filterForm.match_time[0],
                    match_end_time: state.filterForm.match_time[1],
                    its_me: state.filterForm.its_me,
                    page: 1,
                    page_size: state.orderListtotal
                }
                if (body.league_name == 'all') {
                    delete body.league_name
                }
                if (body.task_type == 'all') {
                    delete body.task_type
                }
                if (body.its_me == -1) {
                    delete body.its_me
                }
                if (state.filterForm.homeaway == 'all') {
                    delete body.home_away
                } else {
                    let parts = state.filterForm.homeaway.split("-vs-");
                    let beforeVs = parts[0];
                    let afterVs = parts[1];
                    state.matchfilter.forEach(item => {
                        if (item.home == beforeVs && item.away == afterVs) {
                            body.home_away = item
                        }
                    });
                }
                http.post('/order/order_list_bytask_data', body).then((res) => {
                    getExcel(res.data.list)
                })
            } else {
                let body = {
                    user_name: state.filterForm.user_name,
                    sport_type: state.filterForm.sport_type,
                    order_status: state.filterForm.order_status,
                    league_name: state.filterForm.league_name,
                    home_away: {
                        home: "",
                        away: ""
                    },
                    begin_time: state.filterForm.order_time[0],
                    end_time: state.filterForm.order_time[1],
                    page: 1,
                    page_size: state.orderListtotal
                }
                if (body.league_name == 'all') {
                    delete body.league_name
                }
                if (state.filterForm.homeaway == 'all') {
                    delete body.home_away
                } else {
                    let parts = state.filterForm.homeaway.split("-vs-");
                    let beforeVs = parts[0];
                    let afterVs = parts[1];
                    state.matchfilter.forEach(item => {
                        if (item.home == beforeVs && item.away == afterVs) {
                            body.home_away = item
                        }
                    });
                }

                http.post('/order/member_order_list', body).then((res) => {
                    getExcel(res.data.list)
                })
            }

        } else {
            ElMessage({
                message: '暂无可导出数据',
                type: 'warning',
            })
        }
    }

    const getExcel = (data) => {
        console.log(data);
        
        let header1 = []
        let header2 = []
        let bctypes = {
            hga: '皇冠体育',
            ps3838: '平博体育',
            kaiyun: '开云体育',
            isn: '智博体育',
            imsport: 'IM体育',
            manbet165: '万博体育',
            dxvip: '德信体育',
        }

        if (state.activetype == 0) {
            header1 = ['订单号', '时间', '玩法', '主队', '客队', '开赛时间', '联赛', '比分', '盘口', '综合赔率', '下单金额', '下单人类型']
            header2 = [
                '账号',
                '下单人',
                '所属人',
                '平台',
                '状态',
                '赔率',
                '平台单号',
                '下单金额(虚数)',
                '下单金额(实数)',
                '利润/亏损(虚数)',
                '利润/亏损(实数)'
            ]


            let header = [...header1, ...header2]
            let datas = []
            data.forEach(item => {
                let a = [
                    item.id,
                    item.created_at,
                    item.sport_type == 'soccer' ? '足球' : '篮球',
                    item.minfo.home_name,
                    item.minfo.away_name,
                    item.minfo.match_time,
                    item.minfo.league_name,
                    item.score.score,
                    item.pk_odds_key_ch,
                    comprehensiveOdd(item),
                    item.total_stake,
                    item.its_me == 0 ? '他人' : '本人',
                ]
                let a0 = ['', '', '', '', '', '', '', '', '', '', '', '']
                let isone = 0
                console.log(item);
                
                // item.order_data.forEach((item2, index2) => {
                item.order_list.forEach(item3 => {
                    isone += 1
                    let b = [
                        item3.user_name,
                        item3.order_user_name,
                        item3.creat_user_name,
                        bctypes[item3.bc_type],
                        item3.check_status == 0
                            ? '未结算'
                            : '已结算',
                        item3.place_odds_info,
                        item3.bet_id,
                        item3.real_amount,
                        item3.total_amount,
                        item3.win_back.toFixed(2),
                        item3.total_win_back.toFixed(2)
                    ]
                    let c = []
                    if (isone == 1) {
                        c = [...a, ...b]
                    } else {
                        c = [...a0, ...b]
                    }
                    datas.push(c)
                })
            })

            excels(header, datas)
        } else {
            let header = ['平台订单号', '账号', '平台', '下单时间', '玩法', '比赛时间', '联赛', '主队', '客队', '盘口', '赔率', '下单金额', '利润/亏损']
            let datas = []
            data.forEach(item => {
                let a = [
                    item.bet_id,
                    item.user_name,
                    bctypes[item.bc_type],
                    item.place_date,
                    item.sport_type == 'soccer' ? '足球' : '篮球',
                    item.match_time,
                    item.league_name,
                    item.home_name,
                    item.away_name,
                    item.pk_odds_key_ch,
                    item.odd,
                    item.real_amount,
                    item.win_back
                ]
                datas.push(a)
            });
            console.log(header);
            console.log(datas);


            excels(header, datas)
        }


    }

    const statuslabel = (value) => {
        let str = ''
        state.status.forEach(item => {
            if (item.value == value) {
                str = item.label
            }
        });
        return str
    }

    const excels = async (header, datas) => {
        console.log(header);
        console.log(datas);
        
        
        let tasks = {
            all: '全部',
            _reservation_order: '手动下单',
            _copy_order_hand: '手动跟单',
            _copy_order_auto: '自动跟单'

        }
        const worksheetData = [header, ...datas]
        let name = ''
        name += `${state.activetype == 0 ? 'IB订单' : '平台订单'}`
        name += `_任务类型(${tasks[state.filterForm.task_type]})`
        name += `_玩法(${state.filterForm.sport_type == 'soccer' ? '足球' : '篮球'})`
        if (state.activetype == 0) {
            name += `_订单类型(${state.filterForm.its_me == -1 ? '全部' : (state.filterForm.its_me == 0 ? '共享' : '独享')})`
        }

        name += `_联赛(${state.filterForm.league_name == 'all' ? '全部' : state.filterForm.league_name})`
        name += `_赛事(${state.filterForm.homeaway == 'all' ? '全部' : state.filterForm.homeaway})`
        name += `_订单状态(${statuslabel(state.filterForm.order_status)})`
        state.excelsta = false
        const result = await window.electron.dialogSave({ worksheetData: worksheetData, name: name })
        if (result == '取消保存') {
            ElMessage({
                message: result,
                type: 'warning',
            })
        } else if (result == '保存成功') {
            ElMessage({
                message: result,
                type: 'success',
            })
        } else {
            ElMessage.error(result)
        }
    }

    const comprehensiveOdd = row => {
        let a = '-'
        let num1 = 0
        let num2 = 0
        let num3 = 0
        row.order_list.forEach(item => {
            num1 += item.total_amount
            num2 += item.total_amount * item.place_odds_info
        })

        if (num1 != 0) {
            num3 = num2 / num1
            a = num3.toFixed(3)
        }
        return a
    }

    const changeactivebctype = (value) => {
        state.orderList = []
        state.orderListtotal = 0
        state.activetype = value
        filterReset()
    }


    onMounted(async () => {
        initData()
    })

    onUnmounted(() => {
    })


    async function initData() {
        console.log(state.activetype);

        getleaguefilter()
        getTimerange()
        if (state.activetype == 1) {
            getuserLists()
            state.status = [{
                value: 0,
                label: '已结算',
                count: 0
            }]
        } else {
            getorderList()
            getorderfiltercount()
        }


    }


    return {
        state,

        changeactivestatus,
        openOrderfilter,
        changeleaguename,
        filterReset,
        clicksubmit,
        getorderList,
        gethandicapname,
        saveExell,
        changeactivebctype

    }
}
